/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.war.metier;

import com.ejb.metier.IUserManager;
import com.ejb.persistence.Address;
import com.ejb.persistence.User;
import com.ejb.persistence.UserAuthentication;
import com.ejb.persistence.UserType;
import com.war.helpers.HelperDebug;
import com.war.helpers.HelperNavigation;
import com.war.session.UserSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Ambroise
 * Class used to manage users
 */
@ManagedBean(name="userManager")
@RequestScoped
public class UserManager {

    @EJB
    private IUserManager userManager;
    
    /**
	 * Get the EL context. See https://cwiki.apache.org/MYFACES/accessing-one-managed-bean-from-another.html
	 */
	private ELContext elContext = FacesContext.getCurrentInstance().getELContext();
	
	/**
	 * Import the HelperNavigation.
	 */
	private HelperNavigation navigation = (HelperNavigation) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "helperNavigation");
    
    /**
	 * Import the UserSession.
	 */
	private UserSession session = (UserSession) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "userSession");
	
    private String login;
    private String password;
    private String passwordBis;
    private String firstName;
    private String lastName;
    private String email;
    private String responseText;// Unused AJAX try
    private boolean responseSuccess;// Unused AJAX try

    private String country;
    private String city;
    private String zipCode;
    private String line1;
    private String line2;

    public String getResponseText() {
        return responseText;
    }

    public void setResponseText(String responseText) {
        this.responseText = responseText;
    }

    public boolean isResponseSuccess() {
        return responseSuccess;
    }

    public void setResponseSuccess(boolean responseSuccess) {
        this.responseSuccess = responseSuccess;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPasswordBis() {
        return passwordBis;
    }

    public void setPasswordBis(String passwordBis) {
        this.passwordBis = passwordBis;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getZipCode() {
        return zipCode;
    }

    public void setZipCode(String zipCode) {
        this.zipCode = zipCode;
    }

    public String getLine1() {
        return line1;
    }

    public void setLine1(String line1) {
        this.line1 = line1;
    }

    public String getLine2() {
        return line2;
    }

    public void setLine2(String line2) {
        this.line2 = line2;
    }
    
    /**
     * Creates a new instance of UserManager
     */
    public UserManager() {
        
    }
    /**
     * Simple connection.
     * @return Page to load.
     */
    public String validateConn(){
        String retour = "profile?faces-redirect=true";
        String retourAdmin = "administrationMonitoringStocks?faces-redirect=true";
        // If login and password are incorrects, return.
        User user = userManager.validateConn(login, password);

        if(user != null){
            // Login and password are goods.
            this.connectUser();
            this.refreshUserSession(user);

            if(session.getAccessRight().equals(UserType.Libraire)){
                // Admin account.
                HelperDebug.addMessage("Connexion réussie.<br />Vous avez été redirigé vers les stocks critiques.", "success");
                return retourAdmin;
            }else{
                // Member account.
                HelperDebug.addMessage("Connexion réussie.<br />Vous avez été redirigé vers votre profil.", "success");
                return retour;
            }
        }else{
            HelperDebug.addMessage("Le pseudo et/ou le mot de passe est/sont incorrect(s).", "error");
            return "";
        }


    }
    
    public String registration(){
        String retour = "index?faces-redirect=true";
        HashMap<String, Object> m = new HashMap<String, Object>();
        String mess;
        String type = "error";
        if ("".equals(this.city) || "".equals(this.country) || "".equals(this.email) 
                || "".equals(this.firstName) || "".equals(this.lastName) || "".equals(this.line1) 
                || "".equals(this.login) ||"".equals(this.password) 
                || "".equals(this.passwordBis) || "".equals(this.zipCode)){
            mess = "L'un des champs obligatoire n'est pas renseigné.";
            retour = "";
        } else if (!this.password.equals(passwordBis)){
            mess = "Les mots de passe sont différents.";
            retour = "";
        } else {
            Address address = new Address();
            User user = new User();
            UserAuthentication auth = new UserAuthentication();
            
            auth.setLogin(login);
            auth.setPassword(password);
            user.setAddress(address);
            user.setEmail(email);
            user.setFirstName(firstName);
            user.setLastName(lastName);
            user.setType(UserType.Utilisateur);
            user.setUserAuth(auth);
            address.setCity(city);
            address.setCountry(country);
            address.setLine1(line1);
            address.setLine2(line2);
            address.setZipCode(zipCode);
            address.setUser(user);
            
//------------------------try------------------------------
            if(userManager.createAccount(user, address)){
                // Connexion automatique de l'utilisateur.
                user = userManager.validateConn(login, password);
                
                this.connectUser();
                this.refreshUserSession(user);
                
                type = "success";
                mess = "Votre compte a été créé.<br />Vous êtes à présent connecté.<br /><b>Bonne visite !</b>";
            }
            else{
                type = "error";
                mess = "Ce login a déja été utilisé, veuillez réessayer avec un nouveau login.";
                retour = "";
            }
             
//---------------------------------------------------------


        }
        m.put("type", type);
        m.put("message", mess);
        ArrayList<HashMap<String, Object>> messages = this.session.getMessages();
        messages.add(m);
        this.session.setMessages(messages); 
        return retour;
    }
    
    /**
     * Connection with AJAX request.
     * @return Message to display.
     * 
     * @TODO Faire fonctionner ce code qui ne marche pas... La redirection ne génère pas d'erreur mais ne fonctionne pas ! (Ajax ?)
     */
    public String validateConnAjax(){
        if(login.equals("admin") && password.equals("admin")){
            try {
                HelperDebug.addMessage(navigation.getUrl("profile"), "error");
                FacesContext.getCurrentInstance().getExternalContext().redirect("profile.xhtml");
            } catch (IOException ex) {
                HelperDebug.addMessage("Catch", "error");
                Logger.getLogger(UserManager.class.getName()).log(Level.SEVERE, null, ex);
            }
            return "<span class='alert alert-success'>Vous êtes à présent connecté.</span>";
        }
        
        return "<span class='alert alert-error'>Pseudo et/ou mot de passe incorrect(s)</span>";
    }
    
    /**
     * Refresh the user session.
     * @param user 
     */
    public void refreshUserSession(User user){
        session.setUserId(user.getId());
        session.setAccessRight(user.getType());
        session.setFirstName(user.getFirstName());
        session.setLastName(user.getLastName());
        session.setLogin(user.getUserAuth().getLogin());
        session.setEmail(user.getEmail());
        session.setAddress(user.getAddress());
    }
    
    /**
     * Connect the user. (Update the user session)
     */
    public void connectUser(){
        session.setIsLogged(true);
    }
    
    /**
     * Disconnect the user. (Update the user session)
     */
    public String disconnectUser(){
        // Get the current session.
        HttpSession currentSession = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        currentSession.invalidate();
        
        HelperDebug.addMessage("Vous avez été déconnecté.", "info");

        return "index?faces-redirect=true";
    }
    
    /**
     * Update the user profile.
     * @return The page to load.
     */
    public String profileUpdate(){
        String retour = "profile?faces-redirect=true";

        String mess;
        String type = "error";
        if ("".equals(this.session.getAddress().getCity()) || "".equals(session.getAddress().getCountry()) || "".equals(session.getEmail()) 
                || "".equals(session.getFirstName()) || "".equals(session.getLastName()) || "".equals(session.getAddress().getLine1()) 
                || "".equals(session.getLogin()) || "".equals(session.getAddress().getZipCode())){
            mess = "L'un des champs obligatoire n'est pas renseigné.";
            retour = "";
        } else if (!session.getPassword().equals(session.getPasswordBis())){
            mess = "Les mots de passe sont différents.";
            retour = "";
        } else {
            Address address = new Address();
            User user = new User();
            User lastUser = userManager.getClientInfo(session.getUserId());
            UserAuthentication auth = new UserAuthentication();

            auth.setLogin(session.getLogin());
            // If the password is empty, use the value in the database.
            auth.setPassword(("".equals(session.getPassword()))? lastUser.getUserAuth().getPassword() : session.getPassword());
            user.setUserAuth(auth);
            user.setId(session.getUserId());
            user.setEmail(session.getEmail());
            user.setFirstName(session.getFirstName());
            user.setLastName(session.getLastName());
            user.setType(session.getAccessRight());
            address.setId(session.getAddress().getId());
            address.setCity(session.getAddress().getCity());
            address.setCountry(session.getAddress().getCountry());
            address.setLine1(session.getAddress().getLine1());
            address.setLine2(session.getAddress().getLine2());
            address.setZipCode(session.getAddress().getZipCode());
            address.setUser(user);
            user.setAddress(address);
            
            if(userManager.updateAccount(user, address)){
                // Connexion automatique de l'utilisateur.
                user = userManager.getClientInfo(user.getId());
                
                this.refreshUserSession(user);
                
                type = "success";
                mess = "<b>Votre profil a été modifié.</b>"+("".equals(session.getPassword())? "" : "<br /><br /><b class='orange'>Votre mot de passe a été modifié.</b>") ;
            }
            else{
                mess = "Une erreur est survenue lors de la mise à jour, réessayez.";
                retour = "";
            }
        }
        // Add message to the user session messages.
        HelperDebug.addMessage(mess, type);
        
        return retour;
    }
    
}
